<?php
/**
 * request data processor
 *
 * PHP Version 5.4
 *
 * @author Jason Gao <ghpjc@hotmail.com>
 */
namespace Org\Helper;
use Think\Exception;

/**
 * Class request
 */
class Request
{
    /**
     * Request constructor.
     */
    public function __construct()
    {
        //禁用 request
        $_REQUEST = [];
    }

    /**
     * call method
     *
     * @param string $name      method name
     * @param mixed  $arguments arguments
     *
     * @return mixed
     * @throws Exception
     */
    public function __call($name, $arguments)
    {
        $allowedMethod = ['post', 'put', 'get', 'server'];
        if (!in_array($name, $allowedMethod)) {
            throw new Exception('method does not exist!');
        }

        if (count($arguments)>2) {
            throw new Exception(
                'excepted no more then 2 arguments, but got too many arguments'
            );
        }

        if (!isset($arguments[1])) {
            $arguments[1] = true;
        }

        return $this->_fetch($name, $arguments[0], $arguments[1]);
    }


    /**
     * fetch
     *
     * @param string $type      request type
     * @param string $field     request field
     * @param bool   $useFilter use filter or not
     *
     * @return mixed
     * @throws Exception
     */
    private function _fetch($type, $field, $useFilter = true)
    {
        $value = null;
        $type = strtolower($type);
        switch ($type) {
            case 'get':
                $value = $_GET;
                break;
            case 'post':
                $value = $_POST;
                break;
            case 'put':
                $value = file_get_contents('php://input');
                break;
            case 'server':
                $value = $_SERVER;
                break;
            default:
                throw new Exception('fetch type error for request');
        }

        if (!isset($value[$field])) {
            return null;
        }

        if ($useFilter) {
            return $this->_defaultFilter($value[$field]);
        } else {
            return $value[$field];
        }
    }

    /**
     * default filter for value
     *
     * @param mixed $value input value
     *
     * @return mixed
     */
    private function _defaultFilter($value)
    {
        if (is_array($value)) {
            foreach ($value as $k => $v) {
                $value[$k] = $this->_defaultFilter($v);
            }
        } else {
            $value = trim($value);
            $value = strip_tags($value);
            $value = str_replace('%', '', $value);
            $value = addslashes($value);
        }

        return $value;
    }
}
